package com.baizhi.action;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.service.impl.UserServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

public class UserAction extends ActionSupport {
    /*  成员变量 */
    private User user;
    private String code;
    private String codeuser;


    /*  登录判断 */
    public String login(){
        String username=user.getUsername();
        String password=user.getPassword();

        UserService us = new UserServiceImpl();
        user = us.login(username,password);

        Map<String,Object> session = ServletActionContext.getContext().getSession();
           session.put("username",username);
           session.put("user",user);
           session.put("role",user.getRole());
        System.out.println(user.getRole());



           /* 取出存在session 作用域中的验证码 */
           String code = (String) session.get("code");

        if ( user !=null && codeuser.equals(code) && username !=null && password !=null){

            return "loginsuccess";
        }

        return "exitsuccess";
    }



    /*  退出系统 */
    public String exit(){
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.invalidate();

        return "exitsuccess";
    }


    /*  注册用户 */
    public String register(){

        HttpServletRequest request =ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");

        if (user.getUsername()!=null &&user.getPassword()!=null && codeuser.equals(code)){

            System.out.println(user);
            UserService us =new UserServiceImpl();
            us.register(user);
        }

        return "exitsuccess";
    }




   /* get/set 方法*/
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCodeuser() {
        return codeuser;
    }

    public void setCodeuser(String codeuser) {
        this.codeuser = codeuser;
    }

}
